package com.zjitc.service.imp;

import com.zjitc.common.ServerResponse;
import com.zjitc.mapper.CarMapper;
import com.zjitc.mapper.ProductMapper;
import com.zjitc.pojo.*;
import com.zjitc.service.CarService;
import com.zjitc.utils.old.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/20  17:07
 */
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper cdao;

    @Autowired
    private ProductMapper pdao;

    @Override
    public synchronized void add2car(String uid, int count, String pid) {
        Car car = cdao.checkcar(uid, pid);
        Product product = pdao.findbypid(pid);
        if (car != null) {
                if (car.getCount() < 5) {
                    count = car.getCount() + count;
                    Float subtatal = count * product.getShelfPrice();
                    cdao.updatecar(car.getScid(), count, subtatal);
                }
        } else {
            String scid = Utils.getUUID();
            Float subtotal = product.getShelfPrice() * count;
            cdao.addnew(scid, count, subtotal, uid, pid);
        }
    }

    @Override
    public List<Caritem> findAll(String uid) {
        List<Car> checkcar = cdao.takeoutCar(uid);
        List<Caritem> caritems = new ArrayList<Caritem>();
        for (Car car : checkcar) {
            Product p = pdao.findbypid(car.getPid());
            caritems.add(new Caritem(p, car.getCount(), car.getSubtotal()));
        }
        return caritems;
    }

    @Override
    public int deleteAll(String uid) {
        int i = cdao.deleteAll(uid);
        return i;
    }

    @Override
    public ServerResponse<Car> deletesingle(String pid, String uid) {
        try {
            int del = cdao.deletebypid(pid, uid);
            return ServerResponse.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createError();
        }
    }

    @Override
    public String addAddress(Address address, User user) {
        address.setAid(Utils.getUUID());
        address.setUid(user.getUid());
        int s = cdao.addaddress(address);
        return String.valueOf(s);
    }

    @Override
    public String updateAddress(Address address) {
        int i = cdao.updateaddress(address);
        return String.valueOf(i);
    }

    @Override
    public List<Address> findAllMyAddress(String uid) {
       return cdao.findAlladdress(uid);
    }
}
